import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {NzNotificationService} from "ng-zorro-antd/notification";
import {AbstractControl, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {debounceTime, distinctUntilChanged, first, mergeMap, Observable} from "rxjs";
import {SharedModule} from "@app/shared.module";

import {
  ${TableName!}Service
} from "../../service/${table\-name!}-service";
import {NzUploadFile} from "ng-zorro-antd/upload";

@Component({
  selector: 'app-${table\-name!}-modal',
  templateUrl: './${table\-name!}-modal.component.html',
  styleUrls: ['./${table\-name!}-modal.component.scss'],
  standalone:true,
  imports: [
  SharedModule,
  ],
})
export class ${TableName!}ModalComponent implements OnInit {
  @Input()
  visiable: boolean=false
  @Output()
  visiableChange = new EventEmitter()
  @Output()
  ok = new EventEmitter()
  @Input()
  record: any

  validateForm!: UntypedFormGroup;
  constructor(private fb: UntypedFormBuilder,
              private notification: NzNotificationService,
              private ${tableName!}Service:${TableName!}Service
              ) {}

  ngOnInit() {
    this.validateForm = this.fb.group({
<#list  columns as field>
  ${field.columnName!}: [null, [Validators.required]],
</#list>

    });

  }

  initForm() {
    Object.keys(this.record).forEach(key => {
      this.validateForm.get(key)?.setValue(this.record[key])
    })
  }


  isEdit(){
    return !!this.record.id
  }

  clearForm() {
    this.validateForm.reset()
  }

  handleOk(): void {
    if (this.validateForm.valid) {
      this.${tableName!}Service.add({...this.record,...this.validateForm.value}).subscribe(res=>{
        if (res.status == 200) {
          this.notification.success("Success","submit success")
          this.ok.emit()
          this.closeModal()
        }
      })
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
           control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  handleCancel(): void {
    this.closeModal()
  }

  closeModal() {
    this.clearForm()
    this.visiableChange.emit(false)
  }


}
